<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Admin_News  extends Stourweb_Controller{
    private $_typeid = '115';
    public function before()
    {
        parent::before();

        $this->assign('parentkey',$this->params['parentkey']);
        $this->assign('itemid',$this->params['itemid']);
        $this->assign('weblist',Common::getWebList());
        $this->assign('templetlist',Common::getUserTemplteList('news_show'));//获取上传的用户模板
        $this->assign('typeid',$this->_typeid);

    }
     /*
	  资讯列表
	 */
	public function action_index()
	{

		$action=$this->params['action'];
		if(empty($action))  //显示线路列表页
		{
           $this->assign('kindmenu',Common::getConfig('menu_sub.newskind'));//分类设置项
		   $this->display('admin/news/list');
		}
		else if($action=='read')    //读取列表
		{
			$start=Arr::get($_GET,'start');
			$limit=Arr::get($_GET,'limit');
			$keyword=Arr::get($_GET,'keyword');
			$attr_id = Arr::get($_GET,'attrid');

            $webid = Arr::get($_GET,'webid');
            $webid = $webid=="" ? -1 : $webid;
            $keyword = Common::getKeyword($keyword);
			$sort=json_decode(Arr::get($_GET,'sort'),true);
			$order='order by a.modtime desc';
            $specOrders=array('attrid','kindlist','iconlist','themelist');
			if($sort[0]['property'])
			{
                if($sort[0]['property']=='displayorder')
                    $prefix='';
                else if($sort[0]['property']=='ishidden')
                {
                    $prefix='a.';
                }
                else if($sort[0]['property']=='templet')
                {
                    $prefix='a.';
                }
                else if($sort[0]['property']=='modtime')
                {
                    $prefix='a.';
                }
                else if(in_array($sort[0]['property'],$specOrders))
                {
                    $prefix='order_';
                }
                $order='order by '.$prefix.$sort[0]['property'].' '.$sort[0]['direction'].',a.modtime desc';


			}
			$w="a.id > 0";
			$w.=empty($keyword)?'':" and a.title like '%{$keyword}%'";
			$w.=empty($attr_id)?'':" and (a.category_one = '$attr_id' or a.category_two = '$attr_id')";

            $w.=$webid=='-1' ? '' : " and a.webid=$webid";


            $sql="select a.ishidden,a.id,a.aid,a.title,a.category_one,a.category_two,a.webid,a.addtime,b.displayorder,a.modtime,a.templet from sline_news as a left join sline_allorderlist as b on (a.id=b.aid and b.typeid=".$this->_typeid.")  where $w $order limit $start,$limit";
				

			$totalcount_arr=DB::query(Database::SELECT,"select count(*) as num from sline_news a where $w")->execute()->as_array();
			$list=DB::query(Database::SELECT,$sql)->execute()->as_array();
		
			$new_list=array();
			foreach($list as $k=>$v)
			{
			    $category_one_info = Model_News_Attr::get_category_info($v['category_one']);
			    $category_two_info = Model_News_Attr::get_category_info($v['category_two']);
				$v['category_one_name'] = $category_one_info['attrname'];
			    $v['category_two_name'] = $category_two_info['attrname'];
			    $time = $v['modtime'] ? $v['modtime'] : $v['addtime'];
                $v['modtime']=Common::myDate('Y-m-d',$time);
                $v['url'] = Common::getBaseUrl($v['webid']).'/news/'.$v['aid'].'.html';
				$new_list[]=$v;
			}
			$result['total']=$totalcount_arr[0]['num'];
			$result['lists']=$new_list;
			$result['success']=true;
			echo json_encode($result);
		}
		else if($action=='save')   //保存字段
		{
		   
		}
		else if($action=='delete') //删除某个记录
		{
		   $rawdata=file_get_contents('php://input');
		   $data=json_decode($rawdata);
		   $id=$data->id;
		   
		   if(is_numeric($id)) 
		   {
		        $model=ORM::factory('news',$id);
		        $model->delete_clear();
		   }
		  
		   
		}
		else if($action=='update')//更新字段
		{
			$id=Arr::get($_POST,'id');
			$field=Arr::get($_POST,'field');
			$val=Arr::get($_POST,'val');
			if($field=='displayorder')  //如果是排序
			{
			    $displayorder=empty($val)?9999:$val;
			    if(is_numeric($id))//
				{

					 $order=ORM::factory('allorderlist');
					 $order_mod=$order->where("aid='$id' and typeid=".$this->_typeid." and webid=0")->find();
					
					 if($order_mod->id)  //如果已经存在
					 {
					   $order_mod->displayorder=$displayorder;
					 }
					 else   //如果这个排序不存在
					 {
						$order_mod->displayorder=$displayorder;
						$order_mod->aid=$id;
						$order_mod->webid=0;
						$order_mod->typeid=$this->_typeid;
					 }
					 $order_mod->save();
					 if($order_mod->saved())
					 {
						 echo 'ok';
					 }
					 else
					     echo 'no';

				}
			}
			else if($field=='ishidden')  //如果是隐藏
            {
                if(is_numeric($id))
                {
                    $news_model=ORM::factory('news',$id);
                    $news_model->ishidden=intval($val);
                    $news_model->save();
                    if($news_model->saved())
                    {
                        echo 'ok';
                    }
                    else
                    {
                        echo 'no';
                    }
                }
            }
		}

	}
    /*
     * 添加页面
     * */
    public function action_add()
    {
        $this->assign('webid',0);
        $this->assign('position','添加资讯');
        $this->assign('action','add');
        $this->assign('category_first_list',Model_News_Attr::get_first_category());
        $this->display('admin/news/edit');
    }
    /*
    * 修改页面
    * */
    public function action_edit()
    {
        $productid = $this->params['id'];

        $this->assign('action','edit');
        $info = ORM::factory('news',$productid)->as_array();
        $info['piclist_arr'] =  json_encode(Common::getUploadPicture($info['piclist']));//图片数组
        $extendinfo = Common::getExtendInfo($this->_typeid,$info['id']);
        if (!empty($info['category_two'])) {
            $category_second = Model_News_Attr::get_second_category($info['category_one']);
        } else {
            $category_second = array();
        }
        $this->assign('extendinfo',$extendinfo);//扩展信息
        $this->assign('info',$info);
        $this->assign('category_first_list',Model_News_Attr::get_first_category());
        $this->assign('category_second',$category_second);
        $this->assign('position','修改资讯'.$info['title']);
        $this->display('admin/news/edit');
    }
    /*
     * 保存(ajax)
     * */
    public function action_ajax_save()
    {
        $action = Arr::get($_POST,'action');//当前操作
        $id = Arr::get($_POST,'productid');
        $status = false;
        $webid = Arr::get($_POST,'webid');//所属站点
        $content = Arr::get($_POST,'content');//文章内容
        $templet = Arr::get($_POST,'templet');
        // $bzcontent = Arr::get($_POST, 'bzcontent');
        $allow = Arr::get($_POST, 'allow') ? Arr::get($_POST, 'allow') :'no';//是否 允许封面图片上传
        //图片处理
        $imagestitle = Arr::get($_POST,'imagestitle');
        $images = Arr::get($_POST,'images');
        $imgheadindex = Arr::get($_POST,'imgheadindex');
        $litpic = $images[$imgheadindex];

        //添加操作
        if($action == 'add' && empty($id))
        {
            $model = ORM::factory('news');
            $model->aid = Common::getLastAid('sline_news',$webid);
            $model->addtime = time();
            $model->modtime = time();
        }
        else
        {
            $model = ORM::factory('news',$id);
            $model->modtime = time();
            if($model->webid != $webid) //如果更改了webid重新生成aid
            {
               $aid = Common::getLastAid('sline_news',$webid);
               $model->aid = $aid;
            }
        }

        $model->litpic = $litpic;
        // $content = $templet == 'moban2' ? $content : $bzcontent;
        $download_litpic = '';
        if ($allow == 'usecontentpic') {
            $download_litpic = Model_News::dowload_picture($content);
            $model->litpic = empty($download_litpic) ? $model->litpic : $download_litpic;
        }
        $piclist_arr=array();
        $has_download_litpic = false;
        for($i=1;isset($images[$i]);$i++)
        {
            $desc = isset($imagestitle[$i]) ? $imagestitle[$i] : '';
            $pic = !empty($desc) ? $images[$i].'||'.$desc : $images[$i];
            $piclist_arr[]= $pic;
            if ($images[$i] == $download_litpic) {
                $has_download_litpic = true;
            }
        }
        if (!empty($download_litpic) && !$has_download_litpic) {
            $piclist_arr[] = $download_litpic;
        }
        $model->piclist = implode(',', $piclist_arr);
        $summary = Arr::get($_POST,'summary');

        $summary = strlen($summary)<4 && !empty($content)? mb_substr(strip_tags($content), 0, 140, 'utf-8').'...' : $summary;
        $webid = Arr::get($_POST,'webid');
        $category_one = Arr::get($_POST,'category_one');
        $category_two = Arr::get($_POST,'category_two');

        $model->title = Arr::get($_POST,'title');
        $model->fromsite = Arr::get($_POST,'fromsite');
        $model->author = Arr::get($_POST,'author');
        $model->webid = $webid;
        $link = new Model_Tool_Link();
        $model->content = $link->keywordReplaceBody(Arr::get($_POST, 'content'), 12);
        // $model->content = $content;
        $model->comefrom = Arr::get($_POST,'comefrom');
        $model->ishidden = Arr::get($_POST,'ishidden')?Arr::get($_POST,'ishidden'):0;//显示隐藏
        $model->seotitle = Arr::get($_POST,'seotitle');//优化标题
        $model->tagword = Arr::get($_POST,'tagword');
        $model->keyword = Arr::get($_POST,'keyword');
        $model->description = Arr::get($_POST,'description');
        $model->shownum = Arr::get($_POST,'shownum')? Arr::get($_POST,'shownum'):0;
        $model->has_msg = intval($_POST['has_msg']);
        $model->category_one = $category_one;//分类1
        $model->category_two = $category_two;//分类2
        $model->templet = $templet;
        $model->summary = $summary;
        $model->attachment = Arr::get($_POST,'attachment');



        if($action=='add' && empty($id))
        {
            $model->create();

        }
        else
        {
            $model->update();
        }
        Common::saveExtendData($this->_typeid,$id,$_POST);//扩展信息保存

        if($model->saved())
        {
            if($action=='add')
            {
                if($model->has_msg==1 && empty($model->ishidden) && empty($id))
                {
                    Model_Message::add_news_msg(200, 0, $model->id, $model->as_array());
                }
                $productid = $model->id; //插入的产品id

            }
            else
            {
                $productid =null;
            }

            $status = true;
        }
        echo json_encode(array('status'=>$status,'productid'=>$productid));

    }

    /*
    * 删除附件
    * */
    public function action_ajax_del_attach()
    {
        $id =Arr::get($_POST,'articleid');

        $doc = ORM::factory('news',$id)->get('attachment');

        if($doc)
        {
            $path = BASEPATH.$doc;
            @unlink($path);
        }
        echo json_encode(array('status'=>1));
    }

    /**
     * @function 获取下级栏目
     */
    public function action_ajax_get_category_next()
    {
        $category_id = Arr::get($_POST,'category_id');
        $is_pid = intval(Arr::get($_POST,'is_pid'));

        if($is_pid)
        {
            $out = Model_News_Attr::get_second_category($category_id);
        }
        else
        {
            $category_info = Model_News_Attr::get_category_info($category_id);
            $out = Model_News_Attr::get_second_category($category_info['pid']);
        }
        if(is_array($out))
        {
            echo json_encode(array('status' => 1,'list' => $out));
        }

    }

    /**
     * 站内通知
     */
    public function action_message()
    {
        $msg = DB::select()->from('message_config')->and_where('type','=',200)->execute()->current();
        $this->assign('msg',$msg);
        $this->display('stourtravel/message/order');
        $this->display('admin/news/message');
    }

    //通知保存
    public function action_ajax_save_message()
    {
        $content = $_POST['content'];
        $msg_model = ORM::factory('message_config')->where('type','=',200)->find();
        $msg_model->type = 200;
        $msg_model->isopen = 1;
        $msg_model->content = $content;
        $msg_model->save();
        echo json_encode(array('status'=>true));
    }



	

}